package com.qqtech.qquan.user.service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.google.common.base.Strings;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import com.qqtech.core.common.cache.Cache;
import com.qqtech.core.common.util.SettingCfgUtil;
import com.qqtech.core.frame.dao.BaseDao;
import com.qqtech.core.frame.service.BaseServiceImpl;
import com.qqtech.qquan.user.dao.UserSysDictDao;
import com.qqtech.qquan.user.model.UserSysDict;

@Service
public class UserSysDictServiceImpl extends BaseServiceImpl<UserSysDict>
		implements UserSysDictService, Cache<String, List<UserSysDict>> {
	public static final Logger log = LoggerFactory.getLogger(UserSysDictServiceImpl.class);

	@Resource
	private UserSysDictDao userSysDictDao;

	@Override
	protected BaseDao<UserSysDict> getBaseDao() {
		return userSysDictDao;
	}

	private LoadingCache<String, List<UserSysDict>> caches = CacheBuilder.newBuilder().recordStats()
			.expireAfterWrite(
					SettingCfgUtil.getConfigHelper("qquan-cfg.properties").getIntValue("paramcache.expire.mins"),
					TimeUnit.MINUTES)
			.build(new CacheLoader<String, List<UserSysDict>>() {
				public List<UserSysDict> load(String dictType) {
					UserSysDict sysDict = new UserSysDict();
					sysDict.setType(dictType);
					List<UserSysDict> sysDictList = userSysDictDao.queryList(sysDict);
					if (sysDictList != null) {
						return sysDictList;
					}
					return Lists.newArrayList();
				}
			});

	public String dictValue(String dictType, String dictKey) {
		if (Strings.isNullOrEmpty(dictType) || Strings.isNullOrEmpty(dictKey)) {
			return "";
		}
		List<UserSysDict> dicts = caches.getUnchecked(dictType);
		for (UserSysDict dict : dicts) {
			if (dictKey.equals(dict.getCode())) {
				return dict.getName();
			}
		}
		return "";
	}

	@Override
	public List<UserSysDict> get(String dictType) {
		return caches.getUnchecked(dictType);
	}

	@Override
	public void clear(String dictType) {
		caches.invalidate(dictType);
	}

	@Override
	public void clearAll() {
		caches.invalidateAll();
	}

}